package com.goxplanet;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import io.grpc.protobuf.services.ProtoReflectionService;
import static java.lang.System.exit;

/**
 * Hello world!
 *
 */
public class App 
{
    private Server server;

    private void start(int port) throws IOException {
        MarketDataService service =  new MarketDataService();
        server = ServerBuilder.forPort(port)
                .addService(service)
                .addService(ProtoReflectionService.newInstance())
                .build()
                .start();
        System.out.println("starting grpc server at " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                try {
                    App.this.stop();
                } catch (InterruptedException e) {
                    e.printStackTrace(System.err);
                }
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() throws InterruptedException {
        if (server != null) {
            server.shutdown().awaitTermination(5, TimeUnit.SECONDS);
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 50051;
//        if(args.length > 0){
//            port = Integer.parseInt(args[0]);
//        }
        final App server = new App();
        server.start(port);

        server.blockUntilShutdown();
    }
}
